package cn.rengy.web.framework.wxmp;

import java.io.InputStream;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.rengy.lang.ResultEntity;
import cn.rengy.lang.WeChatException;
import cn.rengy.tool.core.util.ExceptionPrintUtils;
import cn.rengy.tpa.wxmp.event.EventType;
import cn.rengy.tpa.wxmp.event.MsgType;
import cn.rengy.tpa.wxmp.param.SignatureParam;
import cn.rengy.tpa.wxmp.request.WechatRequest;
import cn.rengy.tpa.wxmp.response.ArticleResponse;
import cn.rengy.tpa.wxmp.response.ImageResponse;
import cn.rengy.tpa.wxmp.response.MusicResponse;
import cn.rengy.tpa.wxmp.response.TransInfoResponse;
import cn.rengy.tpa.wxmp.response.VideoResponse;
import cn.rengy.tpa.wxmp.response.VoiceResponse;
import cn.rengy.tpa.wxmp.response.WechatResponse;
import cn.rengy.tpa.wxmp.token.AccessToken;
import cn.rengy.tpa.wxmp.user.LanguageType;
import cn.rengy.tpa.wxmp.user.User;
import cn.rengy.tpa.wxmp.user.UserManager;
import cn.rengy.web.framework.id.IdGenerator;

import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.support.DataConverterImpl;
import cn.rengy.web.framework.sys.user.entity.CenterTpUserResult;
import cn.rengy.web.framework.wxmp.pub.qrcode.ScanQrcodeDTO;
import cn.rengy.web.framework.wxmp.token.AccessTokenCacheService;
import cn.rengy.web.framework.wxmp.user.WxUserPO;
import cn.rengy.web.framework.wxmp.user.WxUserService;

/**
 *
 */
@Service
public class WechatService {
	private static Logger logger = LoggerFactory.getLogger(WechatService.class);
	@Autowired
	private WxAppService wxAppService;
	@Autowired
	private AccessTokenCacheService accessTokenCacheService;
	@Autowired
	private DbService dbService;
	@Autowired
	private IdGenerator idGenerator;
	@Autowired
	private WxUserService wxUserService;
	@Autowired(required = false)
	private WechatEventService wechatEventService;
	@Autowired
	private DataConverterImpl dataConverterImpl;

	private RedisTemplate<Object, Object> redisTemplate;
	@Autowired(required = false)
	public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	@Autowired
	private RestTemplate restTemplate;
//	public static String[] CDATA_TAG = {"ToUserName",
//			"FromUserName","MsgType","Event","MsgId","Content","MediaId","Title","Description","MusicUrl","HQMusicUrl","ThumbMediaId",
//			"PicUrl","Url"
//			};
	public String execute(String appid,Long company_id,String appToken,SignatureParam signatureParam,InputStream inputStream){
		//logger.debug("WechatSupport run");
		String signature =signatureParam.getSignature();
		String timestamp = signatureParam.getTimestamp();
		String nonce = signatureParam.getNonce();
		String echostr = signatureParam.getEchostr();
		
		if(!check(signature, timestamp,  nonce, appToken)){
			return "error";
		}
		if(StringUtils.isNotBlank(echostr)){
     		return echostr;
		}
		WechatRequest wechatRequest=null;
		try {
			wechatRequest=dataConverterImpl.xmlToBean(inputStream, WechatRequest.class);
		} catch (Exception e) {
			logger.error("post data deal failed!");
			logger.error(ExceptionPrintUtils.getTrace(e));
			return "success";
		}
		WechatResponse wechatResponse = new WechatResponse();
		//分发消息，得到响应
		String result = dispatch( appid,wechatResponse,wechatRequest);
		//logger.info("response data:" + result);
		return result;
	}
	public boolean check(String signature, 
			String timestamp,String  nonce,String appToken){
		String[] sa = {appToken, timestamp, nonce};
		Arrays.sort(sa);
		String sortStr = sa[0] + sa[1] + sa[2];
		String sha1= DigestUtils.sha1Hex(sortStr);
		return sha1.equals(signature);
	}
	
	/**
	 * 分发处理，得到响应
	 * @return
	 */
	private String dispatch(String appid,WechatResponse wechatResponse,WechatRequest wechatRequest) {
		
		// 消息分发处理
		dispatchMessage( appid,wechatResponse, wechatRequest);
		// 响应事件
		String result = response( wechatResponse, wechatRequest);
		return result;
	}
	

	

	/**
	 * 消息事件分发
	 */
	private void dispatchMessage(String appid,WechatResponse wechatResponse,WechatRequest wechatRequest){
		//logger.info("distributeMessage start");
		MsgType msgType = MsgType.valueOf(wechatRequest.getMsgType());
		//logger.debug("msgType is {}",msgType.name());
		switch (msgType) {
			case event:
				dispatchEvent(appid,wechatResponse,wechatRequest);
				break;
			case text:
				onText(wechatRequest);
				break;
			case image:
				onImage();
				break;
			case voice:
				onVoice( wechatResponse, wechatRequest);
				break;
			case video:
				onVideo( wechatResponse, wechatRequest);
				break;
			case shortvideo:
				onShortVideo();
				break;
			case location:
				onLocation(  wechatResponse,  wechatRequest);
				break;
			case link:
				onLink(  wechatResponse,  wechatRequest);
				break;
			default:
				onUnknown(  wechatResponse,  wechatRequest);
				break;
		}
	}
	
	/**
	 * event事件分发
	 */
	private void dispatchEvent(String appid,WechatResponse wechatResponse,WechatRequest wechatRequest) {
		//logger.debug("dispatch event,event is {}" , wechatRequest.getEvent());
		EventType event = EventType.valueOf(wechatRequest.getEvent());
		switch (event) {
		case CLICK:
			click( appid, wechatResponse,  wechatRequest);
			break;
		case subscribe:
			subscribe(appid,wechatResponse,  wechatRequest);
			break;
		case unsubscribe:
			unSubscribe(appid,wechatResponse,  wechatRequest);
			break;
		case SCAN:
			scan(appid,wechatResponse,  wechatRequest);
			break;
		case LOCATION:
			location(wechatResponse,  wechatRequest);
			break;
		case VIEW:
			view(wechatResponse,  wechatRequest);
			break;
		case TEMPLATESENDJOBFINISH:
			templateMsgCallback(wechatResponse,  wechatRequest);
			break;
		case scancode_push:
			scanCodePush(wechatResponse,  wechatRequest);
			break;
		case scancode_waitmsg:
			scanCodeWaitMsg(wechatResponse,  wechatRequest);
		    break;
		case pic_sysphoto:
			picSysPhoto(wechatResponse,  wechatRequest);
		    break;
		case pic_photo_or_album:
			picPhotoOrAlbum(wechatResponse,  wechatRequest);
		    break;
		case pic_weixin:
			picWeixin(wechatResponse,  wechatRequest);
		    break;
		case location_select:
			locationSelect(wechatResponse,  wechatRequest);
		    break;
		case kf_create_session:
			kfCreateSession();
			break;
		case kf_close_session:
			kfCloseSession();
			break;
		case kf_switch_session:
			kfSwitchSession();
			break;
		default:
			break;
		}
	}
	

	/**
	 * 返回响应数据
	 * @return
	 */
	private String response(WechatResponse wechatResponse,WechatRequest wechatRequest){
		String result = null;
		if(wechatResponse.isNoResponse()){
			return "success";
		}
		try {
			result=dataConverterImpl.beanToXml(wechatResponse);
			if(result.startsWith("<xml/>")){
				return "success";
			}
		} catch (Exception e) {
			logger.error(ExceptionPrintUtils.getTrace(e));
		}
		return result;
	}
	
	/**
	 * 响应数据基础构造
	 */
	private void responseBase(WechatResponse wechatResponse,WechatRequest wechatRequest){
		wechatResponse.setToUserName(wechatRequest.getFromUserName());
		wechatResponse.setFromUserName(wechatRequest.getToUserName());
		wechatResponse.setCreateTime(wechatRequest.getCreateTime());
	}
	
	/**
	 * 回复文本消息
	 * @param content 回复的消息内容（换行：在content中能够换行，微信客户端就支持换行显示）
	 */
	public void responseText(WechatResponse wechatResponse,WechatRequest wechatRequest,String content){
		responseBase(wechatResponse,wechatRequest);
		wechatResponse.setMsgType(MsgType.text.name());
		wechatResponse.setContent(content);
	}
	
	/**
	 * 回复图片消息
	 * @param mediaId 通过上传多媒体文件，得到的id
	 */
	public void responseImage(WechatResponse wechatResponse,WechatRequest wechatRequest,String mediaId){
		responseBase(wechatResponse,wechatRequest);
		wechatResponse.setMsgType(MsgType.image.name());
		ImageResponse image = new ImageResponse();
		image.setMediaId(mediaId);
		wechatResponse.setImage(image);
	}
	
	/**
	 * 回复语音消息
	 * @param mediaId  通过上传多媒体文件，得到的id
	 */
	public void responseVoice(WechatResponse wechatResponse,WechatRequest wechatRequest,String mediaId){
		responseBase(wechatResponse,wechatRequest);
		wechatResponse.setMsgType(MsgType.voice.name());
		VoiceResponse voice = new VoiceResponse();
		voice.setMediaId(mediaId);
		wechatResponse.setVoice(voice);
	}
	
	/**
	 * 回复视频消息
	 * @param mediaId      通过上传多媒体文件，得到的id
	 * @param title        视频消息的标题
	 * @param description  视频消息的描述
	 */
	public void responseVideo(WechatResponse wechatResponse,WechatRequest wechatRequest,String mediaId,String title,String description){
		VideoResponse video = new VideoResponse();
		video.setMediaId(mediaId);
		video.setTitle(title);
		video.setDescription(description);
		responseVideo( wechatResponse, wechatRequest,video);
	}
	
	/**
	 * 回复视频消息
	 * @param video  视频消息
	 */
	public void responseVideo(WechatResponse wechatResponse,WechatRequest wechatRequest,VideoResponse video){
		responseBase( wechatResponse, wechatRequest);
		wechatResponse.setMsgType(MsgType.video.name());
		wechatResponse.setVideo(video);
	}
	
	/**
	 * 回复音乐消息
	 * @param title         音乐标题
	 * @param description   音乐描述
	 * @param musicURL      音乐链接
	 * @param hQMusicUrl    高质量音乐链接，WIFI环境优先使用该链接播放音乐
	 * @param thumbMediaId  缩略图的媒体id，通过上传多媒体文件，得到的id
	 */
	public void responseMusic(WechatResponse wechatResponse,WechatRequest wechatRequest,String title,String description,
			String musicURL,String hQMusicUrl,String thumbMediaId){
		MusicResponse music = new MusicResponse();
		music.setTitle(title);
		music.setDescription(description);
		music.setMusicURL(musicURL);
		music.setHQMusicUrl(hQMusicUrl);
		music.setThumbMediaId(thumbMediaId);
		responseMusic( wechatResponse, wechatRequest,music);
	}
	
	/**
	 * 回复音乐消息
	 * @param music  音乐消息
	 */
	public void responseMusic(WechatResponse wechatResponse,WechatRequest wechatRequest,MusicResponse music){
		responseBase( wechatResponse, wechatRequest);
		wechatResponse.setMsgType(MsgType.music.name());
		wechatResponse.setMusic(music);
	}
	
	/**
	 * 回复图文消息，单条图文消息
	 * @param title         图文消息标题
	 * @param description   图文消息描述
	 * @param picUrl        图片链接，支持JPG、PNG格式，较好的效果为大图360*200，小图200*200
	 * @param url           点击图文消息跳转链接
	 */
	public void responseNew(WechatResponse wechatResponse,WechatRequest wechatRequest,String title,String description,String picUrl,String url){
		ArticleResponse item = new ArticleResponse();
		item.setTitle(title);
		item.setDescription(description);
		item.setPicUrl(picUrl);
		item.setUrl(url);
		responseNews( wechatResponse, wechatRequest,item);
	}
	
	
	
	/**
	 * 回复图文消息单条
	 * @param item
	 */
	public void responseNews(WechatResponse wechatResponse,WechatRequest wechatRequest,ArticleResponse item){
		List<ArticleResponse> items = new ArrayList<ArticleResponse>();
		items.add(item);
		responseNews( wechatResponse, wechatRequest,items);
	}
	
	/**
	 * 回复多条图文消息
	 * @param items
	 */
	public void responseNews(WechatResponse wechatResponse,WechatRequest wechatRequest,List<ArticleResponse> items){
		responseBase( wechatResponse, wechatRequest);
		wechatResponse.setMsgType(MsgType.news.name());
		wechatResponse.setArticleCount(String.valueOf(items.size()));
		wechatResponse.setArticles(items);
		
	}
	/**
	 * 不回复
	 */
	public void responseNone(WechatResponse wechatResponse,WechatRequest wechatRequest){
		wechatResponse.setNoResponse(true);
		
	}
	/**
	 * 消息转发到多客服
	 */
	public void responseCustomerService(WechatResponse wechatResponse,WechatRequest wechatRequest){
		responseBase( wechatResponse, wechatRequest);
		wechatResponse.setMsgType(MsgType.transfer_customer_service.name());
	}
	/**
	 * 消息转发到指定客服
	 * @param kfAccount 客服账号
	 */
	public void responseCustomerService(WechatResponse wechatResponse,WechatRequest wechatRequest,String kfAccount){
		responseBase( wechatResponse, wechatRequest);
		wechatResponse.setMsgType(MsgType.transfer_customer_service.name());
		wechatResponse.setTransInfo(new TransInfoResponse(kfAccount));
		
	}
	/**
	 * 消息转发到指定客服
	 */
	public void responseCustomerService(WechatResponse wechatResponse,WechatRequest wechatRequest,TransInfoResponse transInfo){
		responseBase( wechatResponse, wechatRequest);
		wechatResponse.setMsgType(MsgType.transfer_customer_service.name());
		wechatResponse.setTransInfo(transInfo);
		
	}
	
	
	/**
	 * 文本消息
	 */
	
	protected void onText(WechatRequest wechatRequest) {
		//String content =  wechatRequest.getContent().trim();
		//String openid=wechatRequest.getFromUserName();
		//更新最后交互时间
		//测试：回复文本消息不能出现链接,this.responseText("<a href=\"www.baidu.com\">测试</a>");
		
	}
	/**
	 * 图片消息
	 * @throws Exception 
	 */
	
	protected void onImage() {
		
	}

	/**
	 * 语音消息
	 */
	
	protected void onVoice(WechatResponse wechatResponse,WechatRequest wechatRequest) {
		//String Format = wechatRequest.getFormat();
		//String MediaId = wechatRequest.getMediaId();//视频消息媒体id，可以调用多媒体文件下载接口拉取数据
		//String MsgId = wechatRequest.getMsgId();
		
		//String result = "语音消息Format:" + Format + ", MediaId:" + MediaId + ", MsgId:" + MsgId;
		//responseText(wechatResponse,wechatRequest,result);	
		//responseVoice(mediaId);
		
		//回复音乐消息
//		MusicResponse music = new MusicResponse();
//		music.setTitle(title);
//		music.setDescription(description);
//		music.setMusicURL(musicURL);
//		music.setHQMusicUrl(hQMusicUrl);
//		music.setThumbMediaId(thumbMediaId);
//		responseMusic(music);
//		
//		responseMusic(title, description, musicURL, hQMusicUrl, thumbMediaId);
	}

	/**
	 * 视频消息
	 */
	
	protected void onVideo(WechatResponse wechatResponse,WechatRequest wechatRequest) {
//		String ThumbMediaId = wechatRequest.getThumbMediaId();
//		String MediaId = wechatRequest.getMediaId();//语音消息媒体id，可以调用多媒体文件下载接口拉取数据
//		String MsgId = wechatRequest.getMsgId();
		
		
		//回复视频消息
//		VideoResponse video = new VideoResponse();
//		video.setTitle(title);
//		video.setDescription(description);
//		video.setMediaId(mediaId);
//		responseVideo(video);
//		
//		responseVideo(mediaId, title, description);
	}
	
	/**
	 * 地理位置消息
	 */
	
	protected void onLocation(WechatResponse wechatResponse,WechatRequest wechatRequest) {
//		String Location_X = wechatRequest.getLocation_X();
//		String Location_Y = wechatRequest.getLocation_Y();
//		String Scale = wechatRequest.getScale();
//		String Label = wechatRequest.getLabel();
//		String MsgId = wechatRequest.getMsgId();
		
	}
	/**
	 * 链接消息
	 */
	
	protected void onLink(WechatResponse wechatResponse,WechatRequest wechatRequest) {
//		String Title = wechatRequest.getTitle();
//		String Description = wechatRequest.getDescription();
//		String Url = wechatRequest.getUrl();
//		String MsgId = wechatRequest.getMsgId();
		
	}
	
	
	/**
	 * 未知消息类型，错误处理
	 */
	
	protected void onUnknown(WechatResponse wechatResponse,WechatRequest wechatRequest) {
		//String msgType = wechatRequest.getMsgType();
		

	}

	/**
	 * 扫描二维码事件
	 */
	
	protected void scan(String appid,WechatResponse wechatResponse,WechatRequest wechatRequest) {
		String openid = wechatRequest.getFromUserName();
		//String Ticket = wechatRequest.getTicket();
		String eventKey=wechatRequest.getEventKey();//场景值即二维码id 以qrscene_开头
		//String ticket = wechatRequest.getTicket();
		if(StringUtils.isNotBlank(eventKey)&&eventKey.startsWith(qrscene)) {//
			wechatRequest.setEventKey(eventKey.substring(8));
		}
		logger.debug("扫描二维码事件openid:{},EventKey:{}",openid,eventKey);
		scan0(appid,openid);
		 
		executorService.execute(new Runnable(){
			@Override
			public void run() {
				try {
					scanByEventKey(  appid,  wechatRequest);
				}catch(Exception e) {
					logger.error(ExceptionUtil.stacktraceToString(e,20000));
				}
				if(wechatEventService!=null) {
					try {
						wechatEventService.scan(appid, wechatRequest);
					}catch(Exception e) {
						logger.error(ExceptionUtil.stacktraceToString(e,20000));
					}
				}
			}
		});
		 
		 responseNone(  wechatResponse,  wechatRequest);
	}

	private String serverIdName="serverId";

	@Value("${tpAppid:0}")
	private Long tpAppid;
	/**
	 * 带场景值二维码扫码时触发
	 */
	private void scanByEventKey(String appid,WechatRequest wechatRequest) {
		String eventKey=wechatRequest.getEventKey();
		if(StringUtils.isNotBlank(eventKey)) {
			ScanQrcodeDTO qrcodeDTO=(ScanQrcodeDTO)redisTemplate.opsForValue().get(eventKey);
			if(qrcodeDTO!=null){
				String notifyUrl=qrcodeDTO.getNotifyUrl();
				if(StringUtils.isNotBlank(notifyUrl)){
					String openid=wechatRequest.getFromUserName();
					WxUserPO wxUserPO=wxUserService.getWxUser(openid, appid);
					//通知调用方扫码用户信息
					CenterTpUserResult scanResult=new CenterTpUserResult();
					scanResult.setHeadimgurl(wxUserPO.getNickname());
					scanResult.setNickname(wxUserPO.getNickname());
					scanResult.setScene_str(qrcodeDTO.getScene_str());
					scanResult.setSex(wxUserPO.getSex());
					scanResult.setTp_appid(tpAppid);
					scanResult.setTp_user_id(wxUserPO.getId());
					restTemplate.postForObject(notifyUrl, scanResult, ResultEntity.class);
				}
			}
		}
	}
	/**
	 * 订阅事件
	 */
	private String qrscene="qrscene_";
	protected void subscribe(String appid,WechatResponse wechatResponse,WechatRequest wechatRequest){
		String openid = wechatRequest.getFromUserName();
		//用户未关注时扫描二维码事件,会多一个EventKey和Ticket节点
		String scene_str=wechatRequest.getEventKey();//场景值即二维码id 以qrscene_开头
		//String ticket = wechatRequest.getTicket();
		if(StringUtils.isNotBlank(scene_str)&&scene_str.startsWith(qrscene)) {//
			scene_str=scene_str.substring(8);
			wechatRequest.setEventKey(scene_str);
		}
		try {
			 subscribe0( wechatResponse, wechatRequest, openid, appid);
		} catch (WeChatException e) {
			logger.error(e.getMessage());
		}
		
		executorService.execute(new Runnable(){
			@Override
			public void run() {
				try {
					scanByEventKey(  appid,  wechatRequest);
				}catch(Exception e) {
					logger.error(ExceptionUtil.stacktraceToString(e,20000));
				}
				
				if(wechatEventService!=null) {
					try {
						wechatEventService.subscribe(appid, wechatRequest);
					}catch(Exception e) {
						logger.error(ExceptionUtil.stacktraceToString(e,20000));
					}
				}
				
				
			}
		});
		
	}
	
	/**
	 * 取消订阅事件
	 */
	
	protected void unSubscribe(String appid,WechatResponse wechatResponse,WechatRequest wechatRequest){
		String openid = wechatRequest.getFromUserName();
		//更新缓存
		long unixTimestamp = Instant.now().getEpochSecond();
		this.dbService.update("update_wx_user_subscribe", 0,unixTimestamp,openid,appid);
		 wechatResponse.setNoResponse(true);
	}
	
	/**
	 * 点击菜单跳转链接时的事件推送
	 */
	
	protected void view(WechatResponse wechatResponse,WechatRequest wechatRequest) {
		//String link =  wechatRequest.getEventKey();
		//String openid=wechatRequest.getFromUserName();
		 responseNone(  wechatResponse,  wechatRequest);
		//responseText("点击菜单跳转链接时的事件推送link:" + link);
	}
	private ExecutorService executorService=Executors.newSingleThreadExecutor();
	/**
	 * 自定义菜单事件
	 */
	
	protected void click(String appid,WechatResponse wechatResponse,WechatRequest wechatRequest) {
		
		//responseText( wechatResponse, wechatRequest,content.toString());
		
		if(wechatEventService!=null) {
			executorService.execute(new Runnable(){
				@Override
				public void run() {
					try {
						wechatEventService.click(appid, wechatRequest);
					}catch(Exception e) {
						logger.error(e.getMessage());
					}
					
				}
			});
		}
		
		responseNone(  wechatResponse,  wechatRequest);
	}
	
	/**
	 * 上报地理位置事件
	 */
	
	protected void location(WechatResponse wechatResponse,WechatRequest wechatRequest) {
		String Longitude = wechatRequest.getLongitude();
		String Latitude = wechatRequest.getLatitude();
		//String Precision = wechatRequest.getPrecision();
		logger.debug("上报地理位置[{}][{}][{}][{}]",wechatRequest.getFromUserName(),Longitude,Latitude,wechatRequest.getCreateTime());
		 responseNone(  wechatResponse,  wechatRequest);
		//responseText(result);
	}
	
	/**
	 * 模板消息发送成功推送事件
	 */
	
	protected void templateMsgCallback(WechatResponse wechatResponse,WechatRequest wechatRequest) {
		//String MsgID = wechatRequest.getMsgId();
		//String Status = wechatRequest.getStatus();
	}
	/**
	 * 弹出地理位置选择器的事件
	 */
	
	protected void locationSelect(WechatResponse wechatResponse,WechatRequest wechatRequest) {
//		String Location_X = wechatRequest.getSendLocationInfo().getLocation_X();
//		String Location_Y = wechatRequest.getSendLocationInfo().getLocation_Y();
//		String Scale = wechatRequest.getSendLocationInfo().getScale();
//		String Label = wechatRequest.getSendLocationInfo().getLabel();
//		String Poiname = wechatRequest.getSendLocationInfo().getPoiname();
	}
	/**
	 * 弹出拍照或者相册发图的事件
	 */
	
	protected void picPhotoOrAlbum(WechatResponse wechatResponse,WechatRequest wechatRequest) {
//		String Count = wechatRequest.getSendPicsInfo().getCount();
//		String PicMd5Sum = "";
//		if(StringUtils.isNotBlank(Count) && !Count.equals("0")){
//			PicMd5Sum = wechatRequest.getSendPicsInfo().getItem().get(0).getPicMd5Sum();
//		}
	}
	/**
	 * 弹出系统拍照发图的事件
	 */
	
	protected void picSysPhoto(WechatResponse wechatResponse,WechatRequest wechatRequest) {
		//String Count = wechatRequest.getSendPicsInfo().getCount();
	}
	/**
	 * 弹出微信相册发图器的事件推送
	 */
	
	protected void picWeixin(WechatResponse wechatResponse,WechatRequest wechatRequest) {
		//String Count = wechatRequest.getSendPicsInfo().getCount();
	}
	/**
	 * 扫码推事件
	 * 
	 */
	
	protected void scanCodePush(WechatResponse wechatResponse,WechatRequest wechatRequest) {
		//String scanType = wechatRequest.getScanCodeInfo().getScanType();
		 wechatResponse.setNoResponse(true);
	}
	/**
	 * 扫码推事件且弹出“消息接收中”提示框的事件
	 */
	
	protected void scanCodeWaitMsg(WechatResponse wechatResponse,WechatRequest wechatRequest){
		//String ScanType = wechatRequest.getScanCodeInfo().getScanType();
		//String scanResult = wechatRequest.getScanCodeInfo().getScanResult();
		//String openid=wechatRequest.getFromUserName();
	}
	
	protected void onShortVideo() {
		// TODO Auto-generated method stub
		
	}
	
	protected void kfCreateSession() {
		// TODO Auto-generated method stub
		
	}
	
	protected void kfCloseSession() {
		// TODO Auto-generated method stub
		
	}
	
	protected void kfSwitchSession() {
		// TODO Auto-generated method stub
		
	}
	private void scan0(String appid,String openid) {
		//如果清除过数据，可能没有用户信息
		AccessToken accessToken=accessTokenCacheService.getAccessToken(appid);
		UserManager userManager=new UserManager(accessToken);
		User user=userManager.getUserInfo(openid,LanguageType.zh_CN);
		WxUserPO wxUser=new WxUserPO();
		BeanUtil.copyProperties(user, wxUser);
		//BeanUtils.copyProperties(user,wxUser);
		wxUser.setAppid(appid);
		//UserAuth userAuth=
				wxUserService.save(wxUser);
		//Long user_id=userAuth.getUser_id();
		//scan00( openid,user_id, scene_str);
	}
	
//	private void scan00(String openid,Long user_id,String scene_str) {
//		if(StringUtils.isNotBlank(scene_str)) {//推广二维码参数
//			//查询用户信息
//			WxQrcodeScanUserDTO user=this.dbService.queryForBean("select_scan_user_info", WxQrcodeScanUserDTO.class, user_id);
//			WxQrcodeScanDTO qr=this.dbService.queryForBean("select_get_qrcode_target_id", WxQrcodeScanDTO.class, scene_str);
//			QrcodeTargetTable target_table=qr.getTarget_table();
//			if(target_table==QrcodeTargetTable.sys_user) {
//				//TODO
//			}
//		}
//	}
	private void subscribe0(WechatResponse wechatResponse,WechatRequest wechatRequest,String openid,String appid)  {
		WxApp wxApp=wxAppService.getApp(appid);
		AccessToken accessToken=accessTokenCacheService.getAccessToken(appid);
		UserManager userManager=new UserManager(accessToken);
		User user=userManager.getUserInfo(openid,LanguageType.zh_CN);
		WxUserPO wxUser=new WxUserPO();
		BeanUtil.copyProperties(user, wxUser);
		//BeanUtils.copyProperties(user,wxUser);
		wxUser.setAppid(appid);
		//保存用户
		//UserAuth userAuth=
				wxUserService.save(wxUser);
		//更新关注状态
		this.dbService.update("update_wx_user_subscribe", 1,user.getSubscribe_time(),openid,appid);
		//Long user_id=userAuth.getUser_id();
		//scan00( openid,user_id, scene_str);
		/*this.executorService.execute(new Runnable(){
		    public void run(){
		    	try{
		    		List<Map<String,Object>> messageList=dbService.queryListBySqlId("select_wx_message_by_openid", openid,appid);
		    		if(messageList!=null){
		    			for(Map<String,Object> msg:messageList){
		    				CustomerMsg customerMsg=new CustomerMsg(accessToken);
		    				String msg_type=(String)msg.get("msg_type");
		    				Long id=(Long)msg.get("id");
		    				try {
		    					String content=(String)msg.get("content");
		    					if("text".equals(msg_type)){
		    						customerMsg.sendText(content, openid);
		    					}else if("mpnews".equals(msg_type)){
		    						//customerMsg.sendNew(title, description, picUrl, url, openid);
		    					}
		    					//发送完更新发送状态
		    					dbService.update("update_wx_message_status", id);
		    				}catch (Exception e) {
		    					logger.error(ExceptionPrintUtils.getTrace(e));
		    				}
		    			}
		    		}
		    	}catch(Exception e){
		    		logger.error(ExceptionPrintUtils.getTrace(e));
		    	}
		    }
		});*/
		
		String welcome_msg = wxApp.getWelcome_msg();
		if(StringUtils.isNotBlank(welcome_msg)){
			 responseText( wechatResponse, wechatRequest,welcome_msg);
			/*try {
				CustomerMsg customerMsg=new CustomerMsg(accessToken);
				customerMsg.sendText(welcome_msg, openid);
			} catch (Exception e) {
				logger.error(ExceptionPrintUtils.getTrace(e));
			}*/
		}
		
	}
	
	 

}
